import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { GridTable } from '../data/grid-table';

@Injectable({
  providedIn: 'root'
})

export class GridTableService {
  constructor(private http: HttpClient) {}

  private dataUrl = 'api/lists';

  // 错误处理
  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      console.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    }
  }

  // 获取列表数据
  getGridlists(): Observable<GridTable[]> {
    return this.http
               .get<GridTable[]>(this.dataUrl)
               .pipe(
                 tap(_ => console.log('fetched grid list')),
                 catchError(this.handleError<GridTable[]>('getGridlists', []))
               );
  }

  // 添加一条数据
  addList(item: GridTable): Observable<GridTable> {
    return this.http
               .post<GridTable>(this.dataUrl, item)
               .pipe(
                 tap(_ => console.log('added new grid list')),
                 catchError(this.handleError<GridTable>('addList'))
               )
  }

  // 删除一条数据
  deleteList(item: GridTable | number): Observable<GridTable> {
    const id = typeof item === 'number' ? item : item.id;
    const url = `${this.dataUrl}/${id}`;
    return this.http
               .delete<GridTable>(url)
               .pipe(
                 tap(_ => console.log(`deleted hero id=${id}`)),
                 catchError(this.handleError<GridTable>('deleteHero'))
               )
  }

  // 修改一条数据
  updateList(item: GridTable): Observable<any> {
    return this.http
               .put(this.dataUrl, item)
               .pipe(
                 tap(_ => console.log('update grid list')),
                 catchError(this.handleError<any>('updateList'))
               )
  }

  // 查询
  searchLists(item: GridTable): Observable<GridTable[]> {
    if (item.id || item.firstName || item.lastName || item.userName || item.email || item.age) {
      let params = '';
      if (item.id) { params += `id=${item.id}&` }
      if (item.firstName) { params += `firstName=${item.firstName}&` }
      if (item.lastName) { params += `lastName=${item.lastName}&` }
      if (item.userName) { params += `userName=${item.userName}&` }
      if (item.email) { params += `email=${item.email}&` }
      if (item.age) { params += `age=${item.age}&` }
      return this.http
                 .get<GridTable[]>(`${this.dataUrl}/?${params}`)
                 .pipe(
                   tap(x => x.length ?
                        console.log('found grid list data') :
                        console.log('cannot found data')),
                   catchError(this.handleError<GridTable[]>('searchLists', []))
                 )
    } else {
      return this.getGridlists();
    }
  }

}
